<script setup>
import { ref, onMounted } from 'vue'
import { fetchGoodsSettle } from '@/api/goodsSettle'
import { ElMessage } from 'element-plus'
import logger from '@/utils/logger'
import { generateSettlement } from '@/api/goodsSettle'
import ViewSettlement from './components/ViewSettlement.vue'

// 列表 & 分页
const tableData = ref([])
const loading = ref(false)
const total = ref(0)

// 选择的结算订单
const selectedOrder = ref([])

// 结算申请单是否显示
const settlementDialogVisible = ref(false)

// 结算申请单数据
let settlementData = ref({})

// 请求参数
const requestParams = ref({
  currentPage: 1,
  pageSize: 10,
  queryFields: {
    goodsName: '',
    xzqhName: '',
    isSettlement: null, // 是否结算状态
  },
})

// 获取结算数据
const fetchSettleData = async () => {
  try {
    loading.value = true
    const params = {
      ...requestParams.value,
      queryFields: {
        goodsName: requestParams.value.queryFields.goodsName?.trim() || null,
        xzqhName: requestParams.value.queryFields.xzqhName?.trim() || null,
        isSettlement: requestParams.value.queryFields.isSettlement,
      },
    }
    const res = await fetchGoodsSettle(params)
    if (res.success && res.data) {
      tableData.value = res.data.list || []
      total.value = res.data.total || 0
    } else {
      tableData.value = []
      total.value = 0
      ElMessage.error(res.msg || '获取商品结算信息失败')
    }
  } catch (error) {
    logger.error('获取商品结算信息失败', error)
    ElMessage.error('获取商品结算信息失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  requestParams.value.currentPage = 1
  fetchSettleData()
}

// 重置
const resetSearch = () => {
  requestParams.value.queryFields.goodsName = ''
  requestParams.value.queryFields.xzqhName = ''
  requestParams.value.queryFields.isSettlement = null
  requestParams.value.currentPage = 1
  fetchSettleData()
}

// 分页事件
const handleSizeChange = (val) => {
  requestParams.value.pageSize = val
  fetchSettleData()
}

const handleCurrentChange = (val) => {
  requestParams.value.currentPage = val
  fetchSettleData()
}

// 表格多选
const handleSelectionChange = (selection) => {
  selectedOrder.value = selection
}

// 结算申请单成功后关闭
const closeSettlementDialog = () => {
  settlementDialogVisible.value = false
  settlementData.value = {}
  fetchSettleData()
}

// 结算申请
const handleApplySettlement = async () => {
  if (selectedOrder.value.length === 0) {
    ElMessage.warning('请至少选择一个订单进行结算')
    return
  }
  try {
    const res = await generateSettlement(selectedOrder.value)
    if (res.success) {
      settlementData.value = res.data
      settlementDialogVisible.value = true
    } else {
      ElMessage.error(res.msg || '生成结算申请单失败')
    }
  } catch (error) {
    logger.error('生成结算申请单失败', error)
    ElMessage.error('生成结算申请单失败')
  }
}

// 挂载
onMounted(() => {
  fetchSettleData()
})
</script>

<template>
  <el-dialog
    v-model="settlementDialogVisible"
    destroy-on-close
    align-center
    title="结算申请单"
    width="70%"
  >
    <ViewSettlement
      :data="settlementData"
      @close="settlementDialogVisible = false"
      @success="closeSettlementDialog"
    />
  </el-dialog>
  <div class="main-container">
    <div class="controller-container">
      <div class="controller-item">
        <el-form :inline="true" :model="requestParams.queryFields">
          <el-form-item label="商品名称">
            <el-input
              v-model="requestParams.queryFields.goodsName"
              placeholder="请输入商品名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><LineMdSearch /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="商品专属区域">
            <el-input
              v-model="requestParams.queryFields.xzqhName"
              placeholder="请输入商品专属区域"
              clearable
              style="width: 200px"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><LineMdSearch /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="结算状态">
            <el-select
              v-model="requestParams.queryFields.isSettlement"
              placeholder="请选择结算状态"
              clearable
              style="width: 200px"
            >
              <el-option :value="true" label="已结算" />
              <el-option :value="false" label="未结算" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <template #icon>
                <el-icon><LineMdSearch /></el-icon>
              </template>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <template #icon>
                <el-icon><LineMdClose /></el-icon>
              </template>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="controller-item">
        <el-form-item>
          <el-button type="primary" @click="handleApplySettlement">
            <template #icon>
              <el-icon><Money /></el-icon>
            </template>
            结算申请单
          </el-button>
        </el-form-item>
      </div>
    </div>
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        height="100%"
        @selection-change="handleSelectionChange"
        row-key="memberOrderDId"
        reserve-selection
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="商品图片" width="100" align="center">
          <template #default="{ row }">
            <el-image
              v-if="row.goodsPicture"
              :src="row.goodsPicture"
              style="width: 60px; height: 60px; border-radius: 4px"
              :preview-src-list="[row.goodsPicture]"
              fit="cover"
              preview-teleported
            />
            <div v-else class="no-image">无图片</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="goodsName"
          show-overflow-tooltip
          label="商品名称"
          min-width="200"
          align="center"
        />
        <el-table-column prop="xzqhName" label="商品专属区域" min-width="120" align="center" />
        <el-table-column prop="payablePoints" label="应付积分" min-width="120" align="center" />
        <el-table-column prop="consumedPoints" label="消费积分" min-width="120" align="center" />
        <el-table-column prop="amount" label="已付金额(元)" min-width="120" align="center" />
        <el-table-column prop="purchaseQuantity" label="购买数量" min-width="100" align="center" />
        <el-table-column prop="createTime" label="创建时间" min-width="160" align="center" />
        <el-table-column prop="specifications" label="规格" min-width="100" align="center" />
        <el-table-column prop="unit" label="单位" min-width="80" align="center" />

        <el-table-column label="结算状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="row.isSettlement ? 'success' : 'danger'">
              {{ row.isSettlement ? '已结算' : '未结算' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="requestParams.currentPage"
          v-model:page-size="requestParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.main-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 10px;
  .controller-container {
    border-radius: 10px;
    background-color: #fff;
    .controller-item {
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }
  .table-container {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border-radius: 10px;
    padding: 10px;
    overflow: hidden;
    gap: 10px;
    .el-table {
      flex: 1;
    }
  }
  .pagination-container {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
